<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>PyMOTW: os(3) &mdash; PyMOTW v1.0 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.0',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="author" title="关于这些文档" href="../about.html" />
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="PyMOTW v1.0 文档" href="../index.html" />
    <link rel="up" title="所有文档" href="index.html" />
    <link rel="next" title="PyMOTW: os(4)" href="os4.html" />
    <link rel="prev" title="PyMOTW: os(2)" href="os2.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="一般索引"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="os4.html" title="PyMOTW: os(4)"
             accesskey="N">后一篇</a> |</li>
        <li class="right" >
          <a href="os2.html" title="PyMOTW: os(2)"
             accesskey="P">前一篇</a> |</li>
        <li><a href="../index.html">PyMOTW v1.0 文档</a> &raquo;</li>
          <li><a href="index.html" accesskey="U">所有文档</a> &raquo;</li> 
      </ul>
    </div>  
    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  
  <div class="section" id="pymotw-os-3">
<h1>PyMOTW: os(3)<a class="headerlink" href="#pymotw-os-3" title="Permalink to this headline">¶</a></h1>
<div class="section" id="id1">
<h2>描述<a class="headerlink" href="#id1" title="Permalink to this headline">¶</a></h2>
<p>前面讲述了如何来处理进程参数和输入/输出，本周我将探讨一些操作文件和目录的函数。</p>
</div>
<div class="section" id="id2">
<h2>文件描述符<a class="headerlink" href="#id2" title="Permalink to this headline">¶</a></h2>
<p>os模块中包含了一些函数集用于处理底层的文件描述符（当前进程打开属主文件所使用的整型），相比file()对象来说这些是更底层的API，在本文中将不会解释什么是文件描述符，它通常可以很好的和file()对象协同工作，更多细节可以参考 <a class="reference" href="http://docs.python.org/lib/os-fd-ops.html">这里</a> 来了解如何使用文件描述符。</p>
</div>
<div class="section" id="id4">
<h2>文件系统权限<a class="headerlink" href="#id4" title="Permalink to this headline">¶</a></h2>
<p>os.access()可以测试一个进程对一个文件是否有可访问权限。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">os</span>

<span class="k">print</span> <span class="s">&#39;Testing:&#39;</span><span class="p">,</span> <span class="n">__file__</span>
<span class="k">print</span> <span class="s">&#39;Exists:&#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">access</span><span class="p">(</span><span class="n">__file__</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">F_OK</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Readable:&#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">access</span><span class="p">(</span><span class="n">__file__</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">R_OK</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Writable:&#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">access</span><span class="p">(</span><span class="n">__file__</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">W_OK</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Executable:&#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">access</span><span class="p">(</span><span class="n">__file__</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">X_OK</span><span class="p">)</span>
</pre></div>
</div>
<p>这个结果将取决于你如何来运行这个示例程序，可能会显示如下：</p>
<div class="highlight-python"><pre>$ python os_access.py
Testing: os_access.py
Exists: True
Readable: True
Writable: True
Executable: False</pre>
</div>
<p>os.access()模块包含了2个特殊的含义，首先，在实际使用open()函数之前使用os.access()函数来判断一个文件是否可访问是没有意义的。这里有个小事实，在函数的两次调用之间可能会改变文件的权限。另外一个含义是该函数适合于大部分扩展的POSIX许可语义的网络文件系统。文件系统对于一个进程对文件有访问权限的POSIX调用会做出响应，在调用open()时，因为某些原因没有通过POSIX的调用测试，那么会报告失败。总之，最好时在特定的模式中使用open()，如果出现错误还可以捕获IOError异常。</p>
<p>如果想获得更多关于文件的信息，可以查阅stat()或者os.lstat（如果你查看的文件一个动态链接的话）。</p>
<div class="highlight-python"><pre>import os
import sys
import time

if len(sys.argv) == 1:
  filename = __file__
  else:
    filename = sys.argv[1]

stat_info = os.stat(filename)

print 'os.stat(%s):' % filename
print '\tSize:', stat_info.st_size
print '\tPermissions:', oct(stat_info.st_mode)
print '\tOwner:', stat_info.st_uid
print '\tDevice:', stat_info.st_dev
print '\tLast modified:', time.ctime(stat_info.st_mtime)</pre>
</div>
<p>再次申明，你得到的结果将取决于你运行的方式，可以尝试向os_stat.py传递不同的文件名看看。</p>
<div class="highlight-python"><pre>$ python os_stat.py
os.stat(os_stat.py):
    Size: 1547
    Permissions: 0100644
    Owner: 527
    Device: 234881026
    Last modified: Sun Jun 10 08:13:26 2007</pre>
</div>
<p>在Unix类型系统上，文件权限可以由chmod()来修改，以整形形式传递。形式值可以用stat模块的常量值来b表示。以下示例了如何来触发用户的可执行权限位。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">os</span>
<span class="k">import</span> <span class="nn">stat</span>

<span class="c"># 使用stat来获取权限设置的时间</span>
<span class="n">existing_permissions</span> <span class="o">=</span> <span class="n">stat</span><span class="o">.</span><span class="n">S_IMODE</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">stat</span><span class="p">(</span><span class="n">__file__</span><span class="p">)</span><span class="o">.</span><span class="n">st_mode</span><span class="p">)</span>

<span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">access</span><span class="p">(</span><span class="n">__file__</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">X_OK</span><span class="p">):</span>
  <span class="k">print</span> <span class="s">&#39;Adding execute permission&#39;</span>
  <span class="n">new_permissions</span> <span class="o">=</span> <span class="n">existing_permissions</span> <span class="o">|</span> <span class="n">stat</span><span class="o">.</span><span class="n">S_IXUSR</span>
<span class="k">else</span><span class="p">:</span>
  <span class="k">print</span> <span class="s">&#39;Removing execute permission&#39;</span>
  <span class="c"># 使用xor来删除用户的可执行权限</span>
  <span class="n">new_permissions</span> <span class="o">=</span> <span class="n">existing_permissions</span> <span class="o">^</span> <span class="n">stat</span><span class="o">.</span><span class="n">S_IXUSR</span>

<span class="n">os</span><span class="o">.</span><span class="n">chmod</span><span class="p">(</span><span class="n">__file__</span><span class="p">,</span> <span class="n">new_permissions</span><span class="p">)</span>
</pre></div>
</div>
<p>运行该脚本前假设你有修改文件模式的权限。</p>
<div class="highlight-python"><pre>$ python os_stat_chmod.py
Adding execute permission
$ python os_stat_chmod.py
Removing execute permission</pre>
</div>
</div>
<div class="section" id="id5">
<h2>目录<a class="headerlink" href="#id5" title="Permalink to this headline">¶</a></h2>
<p>同样提供了一些处理文件系统中目录的函数，包括创建内容列表和删除它们。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">os</span>

<span class="n">dir_name</span> <span class="o">=</span> <span class="s">&#39;os_directories_example&#39;</span>

<span class="k">print</span> <span class="s">&#39;Creating&#39;</span><span class="p">,</span> <span class="n">dir_name</span>
<span class="n">os</span><span class="o">.</span><span class="n">makedirs</span><span class="p">(</span><span class="n">dir_name</span><span class="p">)</span>

<span class="n">file_name</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">dir_name</span><span class="p">,</span> <span class="s">&#39;example.txt&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Creating&#39;</span><span class="p">,</span> <span class="n">file_name</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">file_name</span><span class="p">,</span> <span class="s">&#39;wt&#39;</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
  <span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s">&#39;example file&#39;</span><span class="p">)</span>
<span class="k">finally</span><span class="p">:</span>
  <span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>

<span class="k">print</span> <span class="s">&#39;Listing&#39;</span><span class="p">,</span> <span class="n">dir_name</span>
<span class="k">print</span> <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="n">dir_name</span><span class="p">)</span>

<span class="k">print</span> <span class="s">&#39;Cleaning up&#39;</span>
<span class="n">os</span><span class="o">.</span><span class="n">unlink</span><span class="p">(</span><span class="n">file_name</span><span class="p">)</span>
<span class="n">os</span><span class="o">.</span><span class="n">rmdir</span><span class="p">(</span><span class="n">dir_name</span><span class="p">)</span>
</pre></div>
</div>
<div class="highlight-python"><pre>$ python os_directories.py
Creating os_directories_example
Creating os_directories_example/example.txt
Listing os_directories_example
['example.txt']
Cleaning up</pre>
</div>
<p>有2个函数集用来创建和删除目录，当使用os.mkdir()创建一个新的目录时，其父目录必须存在。当使用os.rmdir()来删除一个目录时候，那么只有目录树的叶子节点（目录的最后一级）可以被删除。相比下，os.makedirs()和os.removedirs()可以操作当前路径下的所有目录，os.makedirs()可以创建路径不存在的目录，os.removedirs()可以删除包含父目录的子目录（当然前提有这个权限）。</p>
</div>
<div class="section" id="id6">
<h2>符号链接<a class="headerlink" href="#id6" title="Permalink to this headline">¶</a></h2>
<p>很多文件系统和平台都支持它，同样有一些函数可以用来处理它们。</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">tempfile</span>

<span class="n">link_name</span> <span class="o">=</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">mktemp</span><span class="p">()</span>

<span class="k">print</span> <span class="s">&#39;Creating link </span><span class="si">%s</span><span class="s">-&gt;</span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">link_name</span><span class="p">,</span> <span class="n">__file__</span><span class="p">)</span>
<span class="n">os</span><span class="o">.</span><span class="n">symlink</span><span class="p">(</span><span class="n">__file__</span><span class="p">,</span> <span class="n">link_name</span><span class="p">)</span>

<span class="n">stat_info</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">lstat</span><span class="p">(</span><span class="n">link_name</span><span class="p">)</span>
<span class="k">print</span> <span class="s">&#39;Permissions:&#39;</span><span class="p">,</span> <span class="nb">oct</span><span class="p">(</span><span class="n">stat_info</span><span class="o">.</span><span class="n">st_mode</span><span class="p">)</span>

<span class="k">print</span> <span class="s">&#39;Points to:&#39;</span><span class="p">,</span> <span class="n">os</span><span class="o">.</span><span class="n">readlink</span><span class="p">(</span><span class="n">link_name</span><span class="p">)</span>

<span class="c"># Cleanup</span>
<span class="n">os</span><span class="o">.</span><span class="n">unlink</span><span class="p">(</span><span class="n">link_name</span><span class="p">)</span>
</pre></div>
</div>
<p>虽然os中包含了os.temparm()来创建临时文件，当时相比tempfile模块还不够安全，在使用中可能会产生RuntimeWarning信息，更好的方法使用tempfile模块。</p>
<div class="highlight-python"><pre>$ python os_symlinks.py
Creating link /tmp/tmpRxRiHn-&gt;os_symlinks.py
Permissions: 0120755
Points to: os_symlinks.py</pre>
</div>
</div>
<div class="section" id="id7">
<h2>访问目录树<a class="headerlink" href="#id7" title="Permalink to this headline">¶</a></h2>
<p>os.walk()可以递归遍历一个目录,对于每一个目录，可以产生一个包含目录路径、当前路径的子目录列表，以及在子目录中的文件，以下示例展示了一个遍历目录的简单方法：</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">os</span><span class="o">,</span> <span class="nn">sys</span>

<span class="c"># 如果没有给定目录列表，那么将使用/tmp</span>
<span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span> <span class="o">==</span> <span class="mf">1</span><span class="p">:</span>
  <span class="n">root</span> <span class="o">=</span> <span class="s">&#39;/tmp&#39;</span>
<span class="k">else</span><span class="p">:</span>
  <span class="n">root</span> <span class="o">=</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mf">1</span><span class="p">]</span>

<span class="k">for</span> <span class="n">dir_name</span><span class="p">,</span> <span class="n">sub_dirs</span><span class="p">,</span> <span class="n">files</span> <span class="ow">in</span> <span class="n">os</span><span class="o">.</span><span class="n">walk</span><span class="p">(</span><span class="n">root</span><span class="p">):</span>
  <span class="k">print</span> <span class="s">&#39;</span><span class="se">\n</span><span class="s">&#39;</span><span class="p">,</span> <span class="n">dir_name</span>
  <span class="c"># 每个子目录名以“/”结尾</span>
  <span class="n">sub_dirs</span> <span class="o">=</span> <span class="p">[</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s">/&#39;</span> <span class="o">%</span> <span class="n">n</span> <span class="k">for</span> <span class="n">n</span> <span class="ow">in</span> <span class="n">sub_dirs</span> <span class="p">]</span>
  <span class="c"># 子目录内容的组合</span>
  <span class="n">contents</span> <span class="o">=</span> <span class="n">sub_dirs</span> <span class="o">+</span> <span class="n">files</span>
  <span class="n">contents</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
  <span class="c"># 显示内容</span>
  <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="n">contents</span><span class="p">:</span>
    <span class="k">print</span> <span class="s">&#39;</span><span class="se">\t</span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">c</span>
</pre></div>
</div>
<div class="highlight-python"><pre>$ python os_walk.py

/tmp
   .KerberosLogin-0--1074266944 (inited,root,local)/
   .KerberosLogin-527-4839472 (inited,gui,tty,local)/
   527/
   cs_cache_lock_527
   cs_cache_lock_92
   emacs527/
   fry.log
   hsperfdata_dhellmann/
   objc_sharing_ppc_4294967294
   objc_sharing_ppc_527
   objc_sharing_ppc_92
   svn.arg.1835l59
   var_backups/

/tmp/.KerberosLogin-527-4839472 (inited,gui,tty,local)
   KLLCCache.lock

/tmp/527
   /tmp/emacs527
   server
   /tmp/hsperfdata_dhellmann
   976

/tmp/var_backups
   infodir.bak
   local.nidump</pre>
</div>
</div>
<div class="section" id="id8">
<h2>后续<a class="headerlink" href="#id8" title="Permalink to this headline">¶</a></h2>
<p>下次，我们讨论os模块中创建和管理进程的函数。</p>
</div>
<div class="section" id="id9">
<h2>参考<a class="headerlink" href="#id9" title="Permalink to this headline">¶</a></h2>
<ul class="simple">
<li><a class="reference" href="http://docs.python.org/lib/os-file-dir.html">Working with Files and Directories</a></li>
<li><a class="reference" href="http://docs.python.org/lib/module-tempfile.html">tempfile module</a></li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../index.html">目录</a></h3>
            <ul>
<li><a class="reference" href="">PyMOTW: os(3)</a><ul>
<li><a class="reference" href="#id1">描述</a></li>
<li><a class="reference" href="#id2">文件描述符</a></li>
<li><a class="reference" href="#id4">文件系统权限</a></li>
<li><a class="reference" href="#id5">目录</a></li>
<li><a class="reference" href="#id6">符号链接</a></li>
<li><a class="reference" href="#id7">访问目录树</a></li>
<li><a class="reference" href="#id8">后续</a></li>
<li><a class="reference" href="#id9">参考</a></li>
</ul>
</li>
</ul>

            <h4>前一个主题</h4>
            <p class="topless"><a href="os2.html" title="前一章节">PyMOTW: os(2)</a></p>
            <h4>后一个主题</h4>
            <p class="topless"><a href="os4.html" title="后一章节">PyMOTW: os(4)</a></p>
            <h3>当前主题</h3>
            <ul class="this-page-menu">
              <li><a href="../_sources/documents/os3.txt">显示页面源码</a></li>
            </ul>
          <h3>快速搜索</h3>
            <form class="search" action="../search.html" method="get">
              <input type="text" name="q" size="18" /> <input type="submit" value="提交" />
              <input type="hidden" name="check_keywords" value="yes" />
              <input type="hidden" name="area" value="default" />
            </form>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>导航</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="一般索引"
             accesskey="I">索引</a></li>
        <li class="right" >
          <a href="os4.html" title="PyMOTW: os(4)"
             accesskey="N">后一篇</a> |</li>
        <li class="right" >
          <a href="os2.html" title="PyMOTW: os(2)"
             accesskey="P">前一篇</a> |</li>
        <li><a href="../index.html">PyMOTW v1.0 文档</a> &raquo;</li>
          <li><a href="index.html" accesskey="U">所有文档</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; <a href="../copyright.html">Copyright</a> 2008, vbarter &amp; liz.
      使用 <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.5.1创建.
    </div>
  </body>
</html>